package com.gwd.task.services.impl;

import com.gwd.task.entity.CodeRepositoryRelateEntity;
import com.gwd.task.model.CodeSubmitRelateDTO;
import com.gwd.task.model.ProjectDTO;
import com.gwd.task.repository.CodeRepositoryRelateRepository;
import com.gwd.task.services.CodeRepositoryRelateServer;
import com.gwd.task.services.ProjectServer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhiyongming
 * @date 2020/12/22 14:53
 */
@Service
public class CodeRepositoryRelateServerImpl implements CodeRepositoryRelateServer {

    @Resource
    private ProjectServer projectServer;
    @Resource
    private CodeRepositoryRelateRepository codeRepositoryRelateRepository;

    @Override
    public List<Long> findByCrId(Long crId) {
        return null;
    }

    @Override
    public void save(Long crId, List<Long> projectIds) {
        codeRepositoryRelateRepository.deleteByCrId(crId);
        if (projectIds.size()!=0) {
            List<CodeRepositoryRelateEntity> list = new ArrayList<>();
            projectIds.forEach(i -> list.add(new CodeRepositoryRelateEntity(crId, i)));

            codeRepositoryRelateRepository.saveAll(list);
        }
    }

    @Override
    public List<CodeSubmitRelateDTO> findProjectByCrId(Long crId) {
        List<ProjectDTO> pList = projectServer.findAll();
        List<CodeSubmitRelateDTO> list
                = codeRepositoryRelateRepository.findByCrId(crId).stream().map(CodeSubmitRelateDTO::new).collect(Collectors.toList());
        list.forEach(c -> pList.forEach(p -> {
            if (c.getProjectId().equals(p.getProjectId())) {
                c.setProjectName(p.getProjectName());
            }
        }));
        return list;
    }

    @Override
    public List<CodeSubmitRelateDTO> findByProject(Long projectId) {
        System.out.println(2333);
        return codeRepositoryRelateRepository.findByProjectId(projectId).stream().map(CodeSubmitRelateDTO::new).collect(Collectors.toList());
    }
}
